package com.thd.wei.controller;

import com.alibaba.fastjson.JSONObject;
import com.thd.wei.entity.AlarmParamsDTO;
import com.thd.wei.service.PushMessageService;
import com.thd.wei.util.CheckoutUtil;
import com.thd.wei.util.Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.thd.wei.service.WeiService.getOpenId;

/**
 *
 * @author : zhangqiang
 * @date : 2020/12/3 13:42
 */
@Controller
@RequestMapping(value = "wx")
public class WeiController{

    /**
     * 公众号appid
     */
    @Value("${wx.appid}")
    private  String appid;

    /**
     * 公众号appSecret
     */
    @Value("${wx.secret}")
    private  String secret;

    @Resource
    PushMessageService pushMessageService;

    @Resource
    private HttpServletRequest request;

    /**
     * 获取微信用户code，并重定向获取用户openId
     * @return
     */
    @GetMapping("/getUserCode")
    public String  getUserCode(){
        String backUrl = "http://fx65hj.natappfree.cc/wx/getUserOpenId";
        String getOpenIdUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri="+ backUrl+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        getOpenIdUrl = getOpenIdUrl.replace("APPID",appid);
        return "redirect:" + getOpenIdUrl;
    }

    /**
     * 获取用户openId
     * @return
     * @throws IOException
     */
    @GetMapping("/getUserOpenId")
    @ResponseBody
    public  String getUserOpenId()throws IOException{
        //获取code
        String code = request.getParameter("code");
        //换取用户openid
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url=url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
        JSONObject result = Util.doGetJson(url);
        JSONObject jSONObject = JSONObject.parseObject(String.valueOf(result));
        String openid = jSONObject.getString("openid");
        return openid;
    }

    /**
     * 向每个用户推送消息
     * @return
     */
    @GetMapping("/sendMessage")
    @ResponseBody
    public String sendMessage(){
        System.out.println(new Date());
        String openId =  "ofhyd6pG3jup026uKaqXg-0YYVcY";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(new Date());
        if(!"".equals(openId)){
            AlarmParamsDTO dto = new AlarmParamsDTO("申请进度", "国家奖学金", "申请通过", time, "成功");
            dto.setOpenId(openId);
            pushMessageService.pushMessage(dto);
        }
        return "success";
    }

    /**
     * 向每个用户推送消息
     * @return
     */
    @GetMapping("/sendAllMessage")
    @ResponseBody
    public String sendAllMessage(){
        String user =  getOpenId();
        if(!"".equals(user)&& user.contains("data")){
            List<String> list = (List<String>) ((JSONObject) JSONObject.parseObject(user).get("data")).get("openid");
            if(!CollectionUtils.isEmpty(list)){
                for(String openId:list){
                    if(!"".equals(openId)){
                        AlarmParamsDTO dto = new AlarmParamsDTO("申请进度", "张飞", "国家奖学金", "申请通过", "成功");
                        dto.setOpenId(openId);
                        pushMessageService.pushMessage(dto);
                    }
                }
                return "success";
            }
        }
        return null;
    }


    /**
     * 微信消息接收和token验证
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/weChatToken")
    public  void weChat(HttpServletRequest request, HttpServletResponse response) {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            System.out.println("signature="+signature+",timestamp="+timestamp+",nonce="+nonce+",echostr"+echostr);
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    PrintWriter print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
